import React, { useEffect, useState } from 'react';
import {
  Table, Modal, Form, Input, Col, message, Button,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  fetchShopList,
  batchShop,
} from '@/services/rentCenter/basicSet';
import { connect } from 'dva';

const { confirm } = Modal
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))

const types = ['', '待确认', '空置', '使用中', '已预订', '确认失败']
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '购物中心',
    key: 'shopCenter',
  },
  {
    title: '商铺号',
    key: 'shopNumber',
  },
  {
    title: '楼栋',
    key: 'building',
  },
  {
    title: '楼层',
    key: 'floor',
  },
  {
    title: '建筑面积（㎡）',
    key: 'constructionArea',
  },
  {
    title: '计租面积（㎡）',
    key: 'rentingArea',
  },
  {
    title: '租金单价（元）',
    key: 'rentUnitPrice',
  },
  {
    title: '物业费单价（元）',
    key: 'propertyUnitPrice',
  },
  {
    title: '状态',
    key: 'status',
    render: params => (
      <span>{types[params.status]}</span>
    ),
  },
  {
    title: '备注',
    key: 'remark',
  },
];

const auditStoreShop = props => {
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [idList, setIdList] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  // 批量导入模态框
  const [showUpload, setUpload] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchShopList(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, []);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };

  // 查询表单
  const getFields = () => (
    <Col span={8}>
      <Form.Item label="模糊条件">
        <Input onChange={v => { setListQuery({ ...listQuery, condition: v.target.value }) }} value={ listQuery.condition } placeholder="楼栋，楼层，商铺号" />
      </Form.Item>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 清空查询条件
  const handleReset = () => {
    setListQuery({
      pageNo: 1,
      pageSize: 10,
    })
    getList({
      pageNo: 1,
      pageSize: 10,
    })
  };
  const showConfirm = () => {
    confirm({
      title: 'Do you want to delete these items?',
      content: 'When clicked the OK button, this dialog will be closed after 1 second',
      onOk() {
        return new Promise((resolve, reject) => {
          batchShop({ storeShopListId: idList }).then(re => {
            if (re.data.code === '0') {
              message.success(re.data.msg)
            }
            getList(listQuery)
          })
        }).catch(() => console.log('Oops errors!'));
      },
      onCancel() {},
    });
  }
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 查询
      case 2:
        return handleSearch();
      // 批量确认
      case 93:
        return showConfirm();
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'checkBox',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      let listid = []
      selectedRows.forEach(v => {
        listid.push(v.id)
      })
      setIdList(listid)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="批量导入"
        visible={showUpload}
        footer={[
          <Button key="back" onClick={() => { setUpload(false) }}>
            关闭
          </Button>,
        ]}
        onCancel={() => { setUpload(false) }}
        destroyOnClose
      >
        hello
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(auditStoreShop));
